package com.itlong.cloud.intercept;

import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.robot.AppRobotLoginCacheVO;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.user.app.IAppUserInfoCacheServiceClient;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <desc>
 *      机器人登录拦截器
 * </desc>
 *
 * @createDate2020/8/6
 **/
@Aspect
@Component
public class RobotLoginIntercept {

    @Autowired
    IAppUserInfoCacheServiceClient userCache;

    @Pointcut("execution(* com.itlong.cloud.controller.robot.*.*(..))")
    public void excludeService(){}

    /**
     * <desc>
     *      通知
     * </desc>
     *
     * @return
     * @Author Zhu.yj
     * @createDate  2020/8/6
     */
//    @Around("excludeService()")
    public Object robotLogin(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token=request.getParameter("token");
        if (token == null) {
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
        }
        if(StringUtils.isNotBlank(token)){
            //解密token拿到用户信息
            AppRobotLoginCacheVO userInfo=userCache.getRobotLoginCache(token);
            if(userInfo==null){
                return new MessageVO(AppErrorCodeEnum.USER_TOKEN_ERROR.getErrorCode());
            }else{
                if (userInfo.getStatus()!=1){
                    return new MessageVO(AppErrorCodeEnum.USER_ACCOUNT_REFUSE.getErrorCode());
                }
                return proceedingJoinPoint.proceed();
            }
        }else{
            return new MessageVO(AppErrorCodeEnum.USER_TOKEN_ERROR.getErrorCode());
        }
    }
}
